/**
 * 框选节点上下左右对齐
 * @param { Node }  nodeSelectedList  antv x6 node元素数组
 * @param { string }  type  对齐类型
 */
type alignType = "alignLeft" | "alignRight" | "alignTop" | "alignBottom" | "alignAngleX" | "alignAngleY"; // 垂直上下左右，X-Y顶点对齐

const alignNodes = (nodeSelectedList: Node[] | any, type: alignType) => {
  const position = `${["alignLeft", "alignRight", "alignAngleX"].includes(type) ? "x" : "y"}`;
  const changePosition = {
    x: 0,
    y: 0,
  };
  nodeSelectedList.sort((a: any, b: any) => {
    return a.position()[position] - b.position()[position];
  });

  if (["alignAngleY", "alignAngleX"].includes(type)) {
    const firstPosition = nodeSelectedList[0].position();
    const lastPosition = nodeSelectedList[nodeSelectedList.length - 1].position();
    const point = {
      x1: firstPosition.x,
      y1: firstPosition.y,
      x2: lastPosition.x,
      y2: lastPosition.y,
    };

    nodeSelectedList.forEach((item: Node | any) => {
      const nodeData = item.getData();
      if (type === "alignAngleX") {
        const x = item.position().x;
        if (point.x2 - point.x1) {
          const y = ((x - point.x1) / (point.x2 - point.x1)) * (point.y2 - point.y1) + point.y1;
          nodeData.x = x;
          nodeData.y = ~y.toFixed(1);
          item.position(x, y);
          item.setData(nodeData);
        }
      } else {
        const y = item.position().y;
        if (point.y2 - point.y1) {
          const x = ((y - point.y1) / (point.y2 - point.y1)) * (point.x2 - point.x1) + point.x1;
          nodeData.x = ~x.toFixed(1);
          nodeData.y = y;
          item.position(x, y);
          item.setData(nodeData);
        }
      }
    });
    return;
  } else if (["alignLeft", "alignRight"].includes(type)) {
    changePosition.x = nodeSelectedList[type === "alignLeft" ? 0 : nodeSelectedList.length - 1].position()[position];
  } else if (["alignTop", "alignBottom"].includes(type)) {
    changePosition.y = nodeSelectedList[type === "alignTop" ? 0 : nodeSelectedList.length - 1].position()[position];
  }
  nodeSelectedList.forEach((item: any) => {
    const nodeData = item.getData();
    nodeData.x = changePosition.x || item.position().x;
    nodeData.y = changePosition.y || item.position().y;
    item.position(nodeData.x, nodeData.y);
    item.setData(nodeData);
  });
};

export { alignNodes };
